﻿using Common;
using Common.Helper;
using Extensions;
using IRepository;
using IService.Blog;
using Microsoft.Extensions.Logging;
using Model;
using Newtonsoft.Json;
using SimpleCaptcha;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;

namespace Service.Blog
{
    public class HomeService: IHomeService
    {
        readonly ILogger<HomeService> logger;
        readonly IBaseRepository baseRepository;
        readonly ICaptcha captcha;
        public HomeService(ILogger<HomeService> _logger, IBaseRepository _baseRepository,ICaptcha _captcha)
        {
            logger = _logger;
            baseRepository = _baseRepository;
            captcha = _captcha;
        }

        /// <summary>
        /// 获取计算题验证码
        /// </summary>
        /// <returns></returns>
        public async Task<MessageModel<NumCode>> GetNumCode()
        {
            try
            {
                Random random = new Random();
                var degree = 1;//难易程度，数字越大越难
                int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
                string[] operators = { "+", "-", "×", "÷" };
                string num1 = string.Empty;
                string oper = operators[random.Next(operators.Length)];
                string num2 = string.Empty;
                if (oper == "÷")
                {
                    for (int i = 0; i < degree; i++)
                    {
                        num1 += nums[random.Next(nums.Length-1)].ToString();
                    }
                    string arr = string.Empty;
                    for (int i = 1; i <= Convert.ToInt32(num1); i++)
                    {
                        if (Convert.ToInt32(num1) % i == 0)
                        {
                            arr += i + ",";
                        }
                    }

                    num2 = arr.Split(',')[random.Next(arr.Split(',').Length-1)];
                }
                else
                {
                    for (int i = 0; i < degree; i++)
                    {
                        num1 += nums[random.Next(nums.Length)].ToString();
                        num2 += nums[random.Next(nums.Length)].ToString();
                    }
                    if (oper=="-"&&Convert.ToInt32(num1)<Convert.ToInt32(num2))
                    {
                        var num = num1;
                        num1 = num2;
                        num2 = num;
                    }
                }

                var formula = num1 + oper + num2;
                int result = 0;
                switch (oper)
                {
                    case "+":
                        result = Convert.ToInt32(num1) + Convert.ToInt32(num2);
                        break;
                    case "-":
                        result = Convert.ToInt32(num1) - Convert.ToInt32(num2);
                        break;
                    case "×":
                        result = Convert.ToInt32(num1) * Convert.ToInt32(num2);
                        break;
                    case "÷":
                        result = Convert.ToInt32(num1) / Convert.ToInt32(num2);
                        break;
                    default:
                        break;
                }
                AppSettings.write("VCID", result.ToString());//存储验证码ID
                return new MessageModel<NumCode>()
                {
                    Code = 200,
                    Data = new NumCode { ExpirationTime=TimeSpan.FromMinutes(1), Formula=formula,Result= result },
                    Message = "调用成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<NumCode>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 判断验证码是否正确
        /// </summary>
        /// <returns></returns>
        public async Task<MessageModel<bool>> Validate(string id, string code)
        {
            try
            {
                bool result = true;
                switch (AppSettings.read("VCIDModel"))
                {
                    case "1":
                        result = captcha.Validate(id, code);
                        break;
                    case "2":
                        result =id==code;
                        break;
                    default:
                        break;
                }
               
                return new MessageModel<bool>() {
                    Code = 200,
                    Message = "获取成功",
                    Success = true,
                    Data=result
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<bool>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 获取图片验证码
        /// </summary>
        /// <returns></returns>
        public async Task<MessageModel<VerifyCode>> GetVerificationCode(string id)
        {
            try
            {
                var info = captcha.Generate(id);
                var stream = new MemoryStream(info.CaptchaByteData);
                VerifyCode verify = new VerifyCode() { Image = stream.ToArray(),Code= info.CaptchaCode };
                var result = verify;
                return new MessageModel<VerifyCode>()
                {
                    Code = 20000,
                    Data = verify,
                    Message = "获取成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<VerifyCode>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 博文统计图
        /// </summary>
        /// <returns></returns>
        public async Task<MessageModel<string>> GetStatistics()
        {
            try
            {
                List<object> dayData = await baseRepository.QueryBySql("select CONVERT(varchar(10), CreatedAt, 120 ) 'name', COUNT(CONVERT(varchar(10), CreatedAt, 120 ))'value' from BArticle GROUP BY CONVERT(varchar(10), CreatedAt, 120 )");
                List<object> monthData = await baseRepository.QueryBySql("select month(CreatedAt) 'month', COUNT(month(CreatedAt))'count' from BArticle GROUP BY month(CreatedAt)");
            
                var list = new {
                    dayData,
                    monthData
                };
                var result = JsonConvert.SerializeObject(list);
                return new MessageModel<string>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }


        /// <summary>
        /// 查询数据库表名及数据量
        /// </summary>
        /// <param name="offset">页数</param>
        /// <param name="limit">每页数</param>
        /// <returns></returns>
        public async Task<MessageModel<string>> GetAllBase()
        {
            try
            {
                List<object> list = await baseRepository.QueryBySql("SELECT a.name, b.rows FROM sysobjects AS a INNER JOIN sysindexes AS b ON a.id = b.id WHERE (a.type = 'u') AND (b.indid IN (0, 1)) ORDER BY b.rows DESC");
                var result = JsonConvert.SerializeObject(list);
                return new MessageModel<string>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

    }
}
